# uncompyle6 version 3.2.3
# Python bytecode 3.6 (3379)
# Decompiled from: Python 3.6.8 |Anaconda custom (64-bit)| (default, Feb 21 2019, 18:30:04) [MSC v.1916 64 bit (AMD64)]
# Embedded file name: site-packages\gevent\win32util.py
"""Error formatting function for Windows.

The code is taken from twisted.python.win32 module.
"""
from __future__ import absolute_import
import os

__all__ = ["formatError"]


class _ErrorFormatter(object):
    """
    Formatter for Windows error messages.
    
    @ivar winError: A callable which takes one integer error number argument
        and returns an L{exceptions.WindowsError} instance for that error (like
        L{ctypes.WinError}).
    
    @ivar formatMessage: A callable which takes one integer error number
        argument and returns a C{str} giving the message for that error (like
        L{win32api.FormatMessage}).
    
    @ivar errorTab: A mapping from integer error numbers to C{str} messages
        which correspond to those errors (like L{socket.errorTab}).
    """

    def __init__(self, WinError, FormatMessage, errorTab):
        self.winError = WinError
        self.formatMessage = FormatMessage
        self.errorTab = errorTab

    @classmethod
    def fromEnvironment(cls):
        """
        Get as many of the platform-specific error translation objects as
        possible and return an instance of C{cls} created with them.
        """
        try:
            from ctypes import WinError
        except ImportError:
            WinError = None

        try:
            from win32api import FormatMessage
        except ImportError:
            FormatMessage = None

        try:
            from socket import errorTab
        except ImportError:
            errorTab = None

        return cls(WinError, FormatMessage, errorTab)

    def formatError(self, errorcode):
        """
        Returns the string associated with a Windows error message, such as the
        ones found in socket.error.
        
        Attempts direct lookup against the win32 API via ctypes and then
        pywin32 if available), then in the error table in the socket module,
        then finally defaulting to C{os.strerror}.
        
        @param errorcode: the Windows error code
        @type errorcode: C{int}
        
        @return: The error message string
        @rtype: C{str}
        """
        if self.winError is not None:
            return str(self.winError(errorcode))
        elif self.formatMessage is not None:
            return self.formatMessage(errorcode)
        else:
            if self.errorTab is not None:
                result = self.errorTab.get(errorcode)
                if result is not None:
                    return result
            return os.strerror(errorcode)


formatError = _ErrorFormatter.fromEnvironment().formatError
